<!--
 * @Author: dawei 664690250@qq.com
 * @Date: 2023-03-28 17:19:37
 * @LastEditors: dawei 664690250@qq.com
 * @LastEditTime: 2023-04-13 16:10:19
 * @FilePath: /hn-talent-ump-vue/src/pages/schedule/ScheduleAnalysis.vue
 * @Description: 请填写文件描述
 * 大佬别走，带带弟弟
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<template>
    <a-card :bordered="false" :loading="loading">
      <a-divider orientation="left">
        总体工作概览
      </a-divider>
      <a-row type="flex" justify="space-around" align="top" class="schedule-analysis">
        <a-col :span="7">
          <div ref="echartsDiv4" class="echarts-outer"></div>
        </a-col>
        <a-col :span="7">
          <div ref="echartsDiv5" class="echarts-outer"></div>
        </a-col>
        <a-col :span="7">
          <div ref="echartsDiv6" class="echarts-outer"></div>
        </a-col>
      </a-row>
      <a-divider orientation="left">
        当前工作详情
      </a-divider>
      <a-row type="flex" justify="space-around" align="top" class="schedule-analysis">
        <a-col :span="7">
          <a-card title="当前应完成的工作">
            <p class="task-item" v-for="(item, idx) in scheduleWorkInfo.currWorkToBeCompleted" :key="idx" >
              <a-button type="link" @click="() => handleNodeItem(item)">
                {{ item.scheduleInfo.content }}
              </a-button>
            </p>
        </a-card>
        </a-col>
        <a-col :span="7">
          <a-card title="当前超期未完成的工作">
            <p class="task-item" v-for="(item, idx) in scheduleWorkInfo.overdueUnfinishedWrok" :key="idx" >
              <a-button type="link" @click="() => handleNodeItem(item)">
                {{ item.scheduleInfo.content }}
              </a-button>
            </p>
          </a-card>
        </a-col>
        <a-col :span="7">
          <div ref="echartsDiv1" class="echarts-outer"></div>
        </a-col>
      </a-row>
      <a-divider orientation="left">
        本周工作计划
      </a-divider>
      <a-row type="flex" justify="space-around" align="top" class="schedule-analysis">
        <a-col :span="7">
          <a-card title="本周要进行的工作">
            <p class="task-item" v-for="(item, idx) in scheduleWorkInfo.currWeekWork" :key="idx" >
              <a-button type="link" @click="() => handleNodeItem(item)">
                {{ item.scheduleInfo.content }}
              </a-button>
            </p>
        </a-card>
        </a-col>
        <a-col :span="7">
          <a-card title="本周要截止的工作">
            <p class="task-item" v-for="(item, idx) in scheduleWorkInfo.currWeekWorkToBeDone" :key="idx" >
              <a-button type="link" @click="() => handleNodeItem(item)">
                {{ item.scheduleInfo.content }}
              </a-button>
            </p>
          </a-card>
        </a-col>
        <a-col :span="7">
          <div ref="echartsDiv2" class="echarts-outer"></div>
        </a-col>
      </a-row>
      <a-divider orientation="left">
        下周工作计划
      </a-divider>
      <a-row type="flex" justify="space-around" align="top" class="schedule-analysis">
        <a-col :span="7">
          <a-card title="下周要进行的工作">
            <p class="task-item" v-for="(item, idx) in scheduleWorkInfo.nextWeekWork" :key="idx" >
              <a-button type="link" @click="() => handleNodeItem(item)">
                {{ item.scheduleInfo.content }}
              </a-button>
            </p>
        </a-card>
        </a-col>
        <a-col :span="7">
          <a-card title="下周要截止的工作">
            <p class="task-item" v-for="(item, idx) in scheduleWorkInfo.nextWeekWorkToBeDone" :key="idx" >
              <a-button type="link" @click="() => handleNodeItem(item)">
                {{ item.scheduleInfo.content }}
              </a-button>
            </p>
          </a-card>
        </a-col>
        <a-col :span="7">
          <div ref="echartsDiv3" class="echarts-outer"></div>
        </a-col>
      </a-row>

      <ScheduleNodeInfoModal :showSchedule="true" ref="infoModalForm"></ScheduleNodeInfoModal>
    </a-card>
  </template>

<script>
import ScheduleNodeInfoModal from './modules/ScheduleNodeInfoModal'
import { getPlanListWithContents } from '@/services/schedule'
import moment from 'moment'
import * as echarts from 'echarts'

export default {
  name: 'ScheduleDashboard',
  components: { ScheduleNodeInfoModal },
  data() {
    return {
      currTime: moment().valueOf(),
      loading: true,
      taskList: []
    }
  },
  watch: {
    $route(to, from) {
      if (to.path === '/schedule/schedule-dashboard' && from.path !== '/schedule/schedule-dashboard') {
        this.loadData()
      }
    }
  },
  mounted() {
    this.loadData()
  },
  computed: {
    scheduleWorkInfo() {
      const res = {
        workInProgress: [], // 进行中的工作
        currWorkToBeCompleted: [], // 截止当前应完成的工作
        overdueUnfinishedWrok: [], // 超期未完成的工作
        finishedWork: [], // 已完成的工作
        unFinishedWork: [], // 未完成的工作
        nextWeekWork: [], // 下周要进行的工作
        nextWeekWorkToBeDone: [], // 下周要截止的工作
        nextWeekWorkDone: [], // 下周已完成的工作
        nextWeekWorkNotDone: [], // 下周未完成的工作
        currWeekWork: [], // 本周要进行的工作
        currWeekWorkToBeDone: [], // 本周要截止的工作
        currWeekWorkDone: [], // 本周已完成的工作
        currWeekWorkNotDone: [], // 本周未完成的工作
        leaderDeptWork: {}, // 牵头部门工作分类
        codeptWork: {}, // 配合部门工作分类
        overdueDeptWork: {} // 超期未完成部门工作分类
      };
      (this.taskList || []).forEach(item => {
        const { contentList, ...rest } = item
        if (Array.isArray(contentList) && !contentList.length) {
          return
        }
        contentList.forEach((node, idx) => {
          if (!node.endTime || !node.startTime) {
            return
          }
          const nodeStartTime = moment(node.startTime).valueOf()
          const nodeEndTime = moment(node.endTime).valueOf()
          const currWeek = moment(this.currTime).format('YYYY-MM-DD')
          const nextWeek = moment(this.currTime).add(1, 'weeks').format('YYYY-MM-DD')
          const currWeekOfStart = moment(currWeek).startOf('week').valueOf()
          const currWeekOfEnd = moment(currWeek).endOf('week').valueOf()
          const nextWeekOfStart = moment(nextWeek).startOf('week').valueOf()
          const nextWeekOfEnd = moment(nextWeek).endOf('week').valueOf()
          const data = {
            ...rest,
            scheduleInfo: {
              ...node
            }
          };
          (node.deptList || []).forEach(dept => {
            if (!Array.isArray(res.leaderDeptWork[dept.deptName])) {
              res.leaderDeptWork[dept.deptName] = []
            }
            if (!Array.isArray(res.codeptWork[dept.deptName])) {
              res.codeptWork[dept.deptName] = []
            }
            if (!Array.isArray(res.overdueUnfinishedWrok[dept.deptName])) {
              res.overdueUnfinishedWrok[dept.deptName] = []
            }
            if (dept.deptType === '1') {
              res.leaderDeptWork[dept.deptName].push(dept)
              if (nodeEndTime < this.currTime && node.status !== '1') {
                res.overdueUnfinishedWrok[dept.deptName].push(dept)
              }
            }
            if (dept.deptType === '2') {
              res.codeptWork[dept.deptName].push(dept)
            }
          })
          if (nodeEndTime > this.currTime && nodeStartTime < this.currTime && node.status !== '1') {
            res.workInProgress.push(data)
          }
          if (nodeEndTime < this.currTime) {
            res.currWorkToBeCompleted.push(data)
          }
          if (nodeEndTime < this.currTime && node.status !== '1') {
            res.overdueUnfinishedWrok.push(data)
          }
          if (node.status === '1') {
            res.finishedWork.push(data)
          }
          if (node.status !== '1') {
            res.unFinishedWork.push(data)
          }
          if ((nodeEndTime > nextWeekOfEnd && nodeStartTime < nextWeekOfEnd) || (nodeEndTime < nextWeekOfEnd && nodeEndTime > nextWeekOfStart)) {
            res.nextWeekWork.push(data)
            if (node.status === '1') {
              res.nextWeekWorkDone.push(data)
            } else {
              res.nextWeekWorkNotDone.push(data)
            }
          }
          if (nodeEndTime < nextWeekOfEnd && nodeEndTime > nextWeekOfStart) {
            res.nextWeekWorkToBeDone.push(data)
          }
          if ((nodeEndTime > currWeekOfEnd && nodeStartTime < currWeekOfEnd) || (nodeEndTime < currWeekOfEnd && nodeEndTime > currWeekOfStart)) {
            res.currWeekWork.push(data)
            if (node.status === '1') {
              res.currWeekWorkDone.push(data)
            } else {
              res.currWeekWorkNotDone.push(data)
            }
          }
          if (nodeEndTime < currWeekOfEnd && nodeEndTime > currWeekOfStart) {
            res.currWeekWorkToBeDone.push(data)
          }
        })
      })
      console.log('scheduleWorkInfo', res)
      return res
    }
  },
  methods: {
    initChart() {
    // 基于准备好的dom，初始化echarts实例
      const echartsDiv1 = echarts.init(this.$refs.echartsDiv1)
      const echartsDiv2 = echarts.init(this.$refs.echartsDiv2)
      const echartsDiv3 = echarts.init(this.$refs.echartsDiv3)
      const echartsDiv4 = echarts.init(this.$refs.echartsDiv4)
      const echartsDiv5 = echarts.init(this.$refs.echartsDiv5)
      const echartsDiv6 = echarts.init(this.$refs.echartsDiv6)
      const finishedWorkLen = this.scheduleWorkInfo.finishedWork.length
      const unFinishedWorkLen = this.scheduleWorkInfo.unFinishedWork.length
      const overdueUnfinishedWrokLen = this.scheduleWorkInfo.overdueUnfinishedWrok.length
      // 绘制图表
      echartsDiv1.setOption({
        title: {
          text: '工作完成情况',
          subtext: `工作总量：${unFinishedWorkLen + finishedWorkLen}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '工作数量',
            type: 'pie',
            radius: '50%',
            data: [
              { value: finishedWorkLen, name: '已完成工作' },
              { value: overdueUnfinishedWrokLen, name: '超期未完成工作' },
              { value: unFinishedWorkLen - overdueUnfinishedWrokLen, name: '进行中的工作' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
      echartsDiv2.setOption({
        title: {
          text: '本周工作完成情况',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['工作总量', '已完成工作量', '未完成工作量']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [this.scheduleWorkInfo.currWeekWork.length, this.scheduleWorkInfo.currWeekWorkDone.length, this.scheduleWorkInfo.currWeekWorkNotDone.length],
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      })
      echartsDiv3.setOption({
        title: {
          text: '下周工作完成情况',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['工作总量', '已完成工作量', '未完成工作量']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [this.scheduleWorkInfo.nextWeekWork.length, this.scheduleWorkInfo.nextWeekWorkDone.length, this.scheduleWorkInfo.nextWeekWorkNotDone.length],
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      })
      echartsDiv4.setOption({
        title: {
          text: '总工作概览',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['工作总量', '已完成工作量', '未完成工作量']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [finishedWorkLen + unFinishedWorkLen, finishedWorkLen, unFinishedWorkLen],
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      })
      echartsDiv5.setOption({
        title: {
          text: '牵头部门工作量占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : 工作数{c} (占比{d}%)'
        },
        series: [
          {
            name: '牵头部门工作占比',
            type: 'pie',
            roseType: 'radius',
            itemStyle: {
              borderRadius: 5
            },
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true
              }
            },
            data: Object.entries(this.scheduleWorkInfo.leaderDeptWork).map(([name, dept]) => {
              return {
                value: dept.length,
                name
              }
            })
          }
        ]
      })
      echartsDiv6.setOption({
        title: {
          text: '配合部门工作量占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : 工作数{c} (占比{d}%)'
        },
        series: [
          {
            name: '配合部门工作量占比',
            type: 'pie',
            radius: '50%',
            itemStyle: {
              borderRadius: 5
            },
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true
              }
            },
            // data: Object.entries(this.scheduleWorkInfo.overdueUnfinishedWrok).map(([name, dept]) => {
            data: Object.entries(this.scheduleWorkInfo.codeptWork).map(([name, dept]) => {
              return {
                value: dept.length,
                name
              }
            })
          }
        ]
      })
    },
    async loadData() {
      const res = await getPlanListWithContents(moment().year().toString())
      if (res && res.code !== 200) {
        // VXETable.modal.message({ content: '获取数据失败', status: 'error' })
        return
      }
      this.loading = false
      this.taskList = res.result
      this.$nextTick(() => {
        this.initChart()
        console.log(this.taskList)
      })
    },
    handleNodeItem(node) {
      const { scheduleInfo, source, category, priority, leaderName, completionMark } = node
      const { progress, startTime, endTime, deptList } = scheduleInfo
      const leadingDept = deptList.find(item => item.deptType === '1')
      const cooperateDept = deptList.filter(item => item.deptType === '2').map(item => ({ ...item, id: item.deptId }))
      if (leadingDept) {
        leadingDept.id = leadingDept.deptId
      }
      const req = {
        source, category, priority, leaderName, completionMark,
        responsibleDpt: node.mgrDept.map(item => item.deptName),
        responsibleDepts: node.mgrDept.map(item => item.deptCode).join(','),
        startEndTime: [node.startTime, node.endTime],
        deptIds: node.mgrDept.map(item => item.deptId),
        ...scheduleInfo,
        progress: progress ? `${progress}%` : '0%',
        startTime: moment.isMoment(startTime) ? startTime.format('YYYY-MM-DD') : startTime,
        endTime: moment.isMoment(endTime) ? endTime.format('YYYY-MM-DD') : endTime,
        leadingDept: leadingDept ? leadingDept.deptName : null,
        cooperateDept: cooperateDept.map(item => item.deptName).join(','),
        attachList: [],
        _leadingDept: leadingDept,
        _cooperateDept: cooperateDept
      }
      this.$refs.infoModalForm.edit(req)
      this.$refs.infoModalForm.title = '查看计划工作详情'
      this.$refs.infoModalForm.disableSubmit = true
    }
  }
}
</script>
<style>
.echarts-outer {
  height: 300px;
}
.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.schedule-analysis .ant-card-body {
  max-height: 300px;
  overflow: scroll;
}
</style>

